package com.ys.peony.ui.activity;

import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ys.peony.R;
import com.ys.peony.app.HttpURL;
import com.ys.peony.app.YSConstant;
import com.ys.peony.base.BaseActivity;
import com.ys.peony.http.JCHttpManagerUtils;
import com.ys.peony.http.base.BaseRespBean;
import com.ys.peony.http.base.BaseRespCallBack;
import com.ys.peony.model.JiekuanrenModel;
import com.ys.peony.model.JiekuanrenResp;
import com.ys.peony.ui.adapter.HistorySearchAdapter;
import com.ys.peony.ui.adapter.JiekuanrenZListViewAdapter;
import com.ys.peony.ui.view.zlistview.widget.ZListView;
import com.ys.peony.utils.JSONUtil;
import com.ys.peony.utils.LoadingProgressUtils;
import com.ys.peony.utils.LogUtil;
import com.ys.peony.utils.NetUtils;
import com.ys.peony.utils.SharePreferencesUtils;
import com.ys.peony.utils.StringUtils;
import com.ys.peony.utils.ToastUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

/**
 * Created by yml on 17/5/12.
 */

public class JiekuanrenListActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.back_btn)
    RelativeLayout backBtn;

    @BindView(R.id.title_name_tv)
    TextView titleNameTv;

    @BindView(R.id.jiekuanren_lv)
    ZListView jiekuanrenListView;

    @BindView(R.id.add_btn)
    TextView addBtn;

    @BindView(R.id.search_et)
    EditText searchET;

    @BindView(R.id.search_delete_img)
    ImageView deleteIcon;

    @BindView(R.id.history_search_rl)
    RelativeLayout historyRl;

    @BindView(R.id.hisroty_search_lv)
    ListView hisKeyLv;

    @BindView(R.id.view_blank)
    LinearLayout view_blank;
    private HistorySearchAdapter keyAdapter;
    private String[] hisKeyList;

    private JiekuanrenZListViewAdapter adapter;
    private int pageNum = 0;

    private List<JiekuanrenModel> list;

    private String searchKeyStr = "";

    @Override
    protected int getContentResId() {
        return R.layout.activity_jiekuanrenliebiao;
    }

    @Override
    public void initView() {
        titleNameTv.setText(getResources().getString(R.string.jiekuanrenliebiao_title));
        backBtn.setOnClickListener(this);
        deleteIcon.setOnClickListener(this);
        searchET.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String etStr = searchET.getText().toString();
                if (!StringUtils.isEmpty(etStr)) {
                    deleteIcon.setVisibility(View.VISIBLE);
                    historyRl.setVisibility(View.GONE);
                } else {
                    deleteIcon.setVisibility(View.GONE);
                    hisKeyList = getSearchKeyHistory();
                    if (hisKeyList == null || hisKeyList.length <= 0) {
                        historyRl.setVisibility(View.GONE);
                    } else {
                        historyRl.setVisibility(View.VISIBLE);
                        keyAdapter.setDate(hisKeyList);
                    }
                }
            }
        });
        keyAdapter = new HistorySearchAdapter(this, hisKeyList);
        hisKeyLv.setAdapter(keyAdapter);
        hisKeyLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == hisKeyList.length) {
                    historyRl.setVisibility(View.GONE);
                    SharePreferencesUtils.getInstance().setKeyValue(YSConstant.SEARCH_KEYS, "");
                } else {
                    searchET.setText(hisKeyList[position]);
                    searchKeyStr = hisKeyList[position];
                    getJieKuanRenList();
                }
            }
        });
        initListView();
    }

    /**
     * 初始化借款人列表
     */
    private void initListView() {
        addBtn.setOnClickListener(this);
        adapter = new JiekuanrenZListViewAdapter(this);
        jiekuanrenListView.setXListViewListener(new ZListView.IXListViewListener() {

            @Override
            public void onRefresh() {
                //刷新
                pageNum = 0;
                getJieKuanRenList();
            }

            @Override
            public void onLoadMore() {
                //加载更多
                getJieKuanRenList();
            }
        });

        jiekuanrenListView.setPullLoadEnable(true);
        jiekuanrenListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                //图片编辑
                Intent it = new Intent(JiekuanrenListActivity.this, BusiLoanInfoActivity.class);
                try {
                    it.putExtra("loanModel", list.get(position - 1));
                    it.putExtra("fileType", "1");
                } catch (Exception e) {

                }
                startActivityForResult(it, YSConstant.ACTIVITY_ADD_YW_CLIENT);
            }

        });

        jiekuanrenListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view,
                                           int position, long id) {
                return true;
            }
        });

        jiekuanrenListView.setAdapter(adapter);

        searchET.setOnKeyListener(new View.OnKeyListener() {

            @Override

            public boolean onKey(View v, int keyCode, KeyEvent event) {

                if (keyCode == KeyEvent.KEYCODE_ENTER) {
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(JiekuanrenListActivity.this.getCurrentFocus()
                                    .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    pageNum = 0;
                    getJieKuanRenList();
                }
                return false;
            }
        });
//        getJieKuanRenList();
    }


    private void getJieKuanRenList() {
        if (!NetUtils.isNetworkConnected(this)) {
            ToastUtils.showToast(this, getResources().getString(R.string.no_net_error));
            return;
        }
        searchKeyStr = StringUtils.trimNull(searchET.getText().toString());
//        LoadingProgressUtils.showProgressDialog(this);
        JCHttpManagerUtils httpManager = new JCHttpManagerUtils();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("userId", Long.parseLong(SharePreferencesUtils.getInstance().getUserModel().getId()));
        params.put("clientName", searchKeyStr);
        params.put("currentPage", pageNum);
        params.put("pageNum", YSConstant.PAGE_NUM);

        httpManager.get(HttpURL.busiLoanPage, params, new BaseRespCallBack(JiekuanrenListActivity.this) {

            public void onRespSuccess(String respStr) {
                saveSearchKeyToHistory();
                LogUtil.i("aaaa", "___list_" + respStr);
                final JiekuanrenResp resp = (JiekuanrenResp) JSONUtil.parseObject(respStr, JiekuanrenResp.class);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        jiekuanrenListView.stopRefresh();
                        jiekuanrenListView.stopLoadMore();
                        boolean isAdd = false;
                        if (resp == null || resp.getDataList() == null || resp.getDataList().size() <= 0) {
                            if (pageNum == 0) {
                                list = null;
                                isAdd = true;
                            }
                        } else {
                            if (pageNum == 0) {
                                list = resp.getDataList();
                            } else {
                                addDate(resp.getDataList());
                            }
                            pageNum++;
                            isAdd = true;
                        }
                        if (isAdd && list != null && list.size() > 0) {
                            hideBlankView();
                            adapter.setData(list);
                        } else {
                            if (pageNum == 0) {
                                showBlankView();
                            }
                        }
                    }
                });
            }

            @Override
            public void onRespFailure(String msg) {
                super.onRespFailure(msg);
                showBlankView();
                ToastUtils.showToast(JiekuanrenListActivity.this, msg);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        pageNum = 0;
        getJieKuanRenList();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_btn:
                finish();
                break;
            case R.id.search_delete_img:
                searchET.setText("");
                deleteIcon.setVisibility(View.GONE);
                break;
            case R.id.add_btn:
                Intent it = new Intent(JiekuanrenListActivity.this, AddClientInfoActivity.class);
                it.putExtra("addFlag", true);
                startActivityForResult(it, YSConstant.ACTIVITY_ADD_YW_CLIENT);
                break;
        }
    }

    private boolean addDate(List<JiekuanrenModel> dataList) {
        if (list == null) {
            list = new ArrayList<JiekuanrenModel>();
        }
        boolean isUpdate = false;
        for (int i = 0; i < dataList.size(); i++) {
            if (!list.contains(dataList.get(i))) {
                list.add(dataList.get(i));
                isUpdate = true;
            }
        }
        return isUpdate;
    }

    /**
     * 移除业务登记
     *
     * @param loanId
     */
    public void delJiekuanrenItem(String loanId) {
        if (!NetUtils.isNetworkConnected(this)) {
            ToastUtils.showToast(this, getResources().getString(R.string.no_net_error));
            return;
        }
        LoadingProgressUtils.showProgressDialog(this);
        JCHttpManagerUtils httpManager = new JCHttpManagerUtils();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("userId", Long.parseLong(SharePreferencesUtils.getInstance().getUserModel().getId()));
        params.put("loanId", loanId);

        httpManager.get(HttpURL.ywdjRemove, params, new BaseRespCallBack() {

            public void onRespSuccess(String respStr) {
                LogUtil.i("aaaa", "___list_" + respStr);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtils.showToast(JiekuanrenListActivity.this, "移除成功");
                        pageNum = 0;
                        getJieKuanRenList();
                    }
                });
            }

            @Override
            public void onRespFailure(String msg) {
                super.onRespFailure(msg);
                ToastUtils.showToast(msg);
            }
        });
    }


    private void saveSearchKeyToHistory() {
        if (StringUtils.isEmpty(searchKeyStr)) {
            return;
        }
        String keyStr = SharePreferencesUtils.getInstance().getValueByKey(YSConstant.SEARCH_KEYS);
        LogUtil.i("bbbb", "*******keyStr**" + keyStr);
        if (StringUtils.isEmpty(keyStr)) {
            SharePreferencesUtils.getInstance().setKeyValue(YSConstant.SEARCH_KEYS, searchKeyStr);
        } else {
            String[] keys = keyStr.split(",");
            LogUtil.i("bbbb", "*******keys**" + keys.length);
            for (String keyItem : keys) {
                if (keyItem.equals(searchKeyStr)) {
                    return;
                }
            }

            if (keys.length < 10) {
                keyStr = keyStr + "," + searchKeyStr;
            } else {
                keyStr = keyStr.substring(keyStr.indexOf(",", 0) + 1);
                keyStr = keyStr + "," + searchKeyStr;
            }
            SharePreferencesUtils.getInstance().setKeyValue(YSConstant.SEARCH_KEYS, keyStr);
        }
    }


    private String[] getSearchKeyHistory() {
        String keyStr = SharePreferencesUtils.getInstance().getValueByKey(YSConstant.SEARCH_KEYS);
        return keyStr.split(",");
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (historyRl.getVisibility() == View.VISIBLE) {
                historyRl.setVisibility(View.GONE);
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (YSConstant.ACTIVITY_ADD_YW_CLIENT == requestCode && resultCode == RESULT_OK) {
            pageNum = 0;
            getJieKuanRenList();
            LogUtil.i("aaaa", "______________refresh_________");
        }
    }

    private void showBlankView() {
        view_blank.setVisibility(View.VISIBLE);
        jiekuanrenListView.setVisibility(View.GONE);
    }

    private void hideBlankView() {
        view_blank.setVisibility(View.GONE);
        jiekuanrenListView.setVisibility(View.VISIBLE);
    }
}
